package com.uottawa.library.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.uottawa.library.domain.TransactionLogger;

public class SystemMonitoringDAO extends BaseDAO {
	
	public void logTransaction(TransactionLogger logger) {
		String query = "INSERT INTO TRANSACTION_LOG (ACTION_NAME, USER_ID, ACTION_TIME) " +
				"VALUES (?, ?, ?)"; 
		Connection connection = getConnection();
		try {
			PreparedStatement stmt = connection.prepareStatement(query);
			stmt.setString(1, logger.getActionName());
			stmt.setInt(2, logger.getUserId());
			stmt.setTimestamp(3, new java.sql.Timestamp(logger.getActionDate().getTime()));
			stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	public List<TransactionLogger> getTransactionsByUserId(int userId) {
		List<TransactionLogger> logs = new ArrayList<TransactionLogger>();
		String query = "SELECT * FROM TRANSACTION_LOG WHERE USER_ID = '"+ userId +"'"; 
		Connection connection = getConnection();
		try {
			Statement stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			while(rs.next()) {
				TransactionLogger log = new TransactionLogger();
				log.setActionName(rs.getString("ACTION_NAME"));
				log.setUserId(rs.getInt("USER_ID"));
				log.setActionDate(rs.getDate("ACTION_TIME"));
				logs.add(log);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return logs;
	}

}
